package shoppingmall.reception.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import shoppingmall.reception.dto.Result;
import shoppingmall.reception.pojo.UserAddress;
import shoppingmall.reception.service.MemberAddressService;

import java.util.List;

/**
 * 平台会员地址控制层-提供会员地址信息服务
 */
@Slf4j
@RestController
public class MemberAddressController {

    //平台会员地址服务层实例
    @Autowired
    private MemberAddressService memberAddressService;

    /**
     * 根据会员用户id查询用户地址列表信息集合
     */
    @GetMapping("/reception/user/address")
    public Result getMemberAddressList (@RequestParam int userId) {
        log.info("查询用户地址信息,用户id={}",userId);
        //调用服务层方法进行查询
        List<UserAddress> memberAddressList = memberAddressService.getMemberAddressList(userId);
        if(memberAddressList.size() != 0){
            return Result.success(memberAddressList);
        }
        return Result.error("未查询到用户地址信息");
    }

    /**
     * 为某个会员用户添加一个收货地址信息
     */
    @PostMapping("/reception/user/address")
    public Result saveMemberAddress (@RequestBody UserAddress userAddress){
        log.info("给会员用户添加收货地址,用户id={}",userAddress.getUserId());
        //调用服务层方法添加地址信息
        boolean isSave = memberAddressService.saveMemberAddress(userAddress);
        if(!isSave){
            //数据添加失败
            return Result.error("收货地址信息添加失败!");
        }
        return Result.success("收货地址信息添加成功!");
    }

    /**
     * 更新某个会员用户的某条收货地址信息
     */
    @PutMapping("/reception/user/address")
    public Result updateMemberAddress (@RequestBody UserAddress userAddress) {
        log.info("给会员用户更新收货地址,用户id={}",userAddress.getUserId());
        //调用服务层方法更新地址信息
        boolean isUpdate = memberAddressService.updateMemberAddress(userAddress);
        if(!isUpdate){
            return Result.error("收货地址信息更新失败!");
        }
        return Result.success("收货地址信息更新成功!");
    }

    /**
     * 删除某个会员用户的某条收货地址信息
     */
    @DeleteMapping("/reception/user/address")
    public Result deleteMemberAddress (@RequestParam int addressId) {
        log.info("给会员用户删除收货地址,收货地址id={}",addressId);
        //调用服务层方法删除地址信息
        boolean isDel = memberAddressService.deleteMemberAddress(addressId);
        if(!isDel){
            return Result.error("收货地址信息删除失败!");
        }
        return Result.success("收货地址信息删除成功!");
    }

    /**
     * 根据地址id查询地址信息
     */
    @GetMapping("/reception/user/address/id")
    public Result getMemberAddressById (@RequestParam int addressId){
        log.info("根据地址id查询地址信息,id={}",addressId);
        //调用服务层方法
        UserAddress addressInfo = memberAddressService.getAddressInfoById(addressId);
        if(addressInfo == null){
            return Result.error("未查询到用户收货地址信息!");
        }
        return Result.success(addressInfo);
    }
}
